/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Validation;

import bean.managed.CreditTermEntityController;
import entity.CustomerAccountEntity;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author sunwei
 */
public class CreditLimitValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

        Double creditLimit = (Double) value;
        
        boolean valid = true;
        CustomerAccountEntity negativeAccount = null;
        
         CreditTermEntityController creditTermEntityController = 
                 (CreditTermEntityController)FacesContext.getCurrentInstance().getExternalContext()
               .getSessionMap().get( "creditTermEntityController");
        for (CustomerAccountEntity account : creditTermEntityController.getCurrent().getCustomerAccounts()) {
            double newCreditBalance = creditLimit - (creditTermEntityController.getOldCreditTerm().getCreditLimit() - account.getCreditBalance());
            if (newCreditBalance < 0) {
                valid = false;
                negativeAccount = account;
                break;
            }
        }

        if (!valid) {
            FacesMessage message = new FacesMessage();
            message.setDetail("New credit limit will result redit balance of account " + negativeAccount.getId() + " to fall below zero.");
            message.setSummary("New credit limit causes problem for existing accounts");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }

    }
}
